import piniaPersistConfig from "../../../config/piniaPersist";
import { defineStore } from "pinia";
import { hasIn } from "lodash"
import fetchApi from '../../api/user/index'
import modelTest from "@/router/modelTest";

export type MenuListType = {
  path: string
   icon: string
    name?:string
   cn_name?:string
   en_name?:string
   pid:string
   id:string
   children?:MenuListType[]
}

export const UserStore = defineStore({
  id: 'app-user',
  state: (): STORE.UserStore => ({
    dic: {},
    currentUser: {},
    menuTree: [],
    permsList:[]
  }),
  getters: {
    getMenuTree(): APIUSER.MenuData[] {
      return this.menuTree ?? []
    },
    getMenuList() {
      const array: MenuListType[] = []
      const fn = (list: APIUSER.MenuData[]) => {
        list.forEach(item => {
          if (item.children) fn(item.children);
          if(hasIn(item,'cn_name')){
            array.push({ path: item.path, icon: item.icon,cn_name:item.cn_name,en_name:item.en_name,pid:item.pid ,id:item.id,children:item.children});
          }else {
            array.push({ path: item.path, icon: item.icon,name:item.name,pid:item.pid ,id:item.id,children:item.children});
          }
        });
      };
      fn(this.menuTree);
      return array
    },
    getDic(): unknown {
      return this.dic ?? {}
    },
    validator():STORE.UserStore['permsList']{
      return (value:string)=> {
        return this.permsList.some((p:string) => {
          return p.indexOf(value) !== -1;
        })
      }
    }
  },
  actions: {
    // 储存当前权限
    setUserStoreData({ dic, currentUser, menuTree,permsList }: STORE.UserStore) {
      this.dic = dic
      this.currentUser = currentUser
      this.menuTree = menuTree
      this.permsList = permsList
    },
    // 重置当前所有数据
    resetState() {
      this.dic = {}
      this.currentUser = {}
      this.menuTree = []
      this.permsList = []
    },
    /**
     * 获取当前用户信息及权限 此方法必须储存 用户角色 及权限 不然会造成路由死循环
     * @returns 返回的菜单及有菜单的权限
     */
    async fetchAuths() {

      const {data} = await fetchApi.loginData()

      const { dict_data_map, current_user, menu_tree, perms_list }  = data


      if(import.meta.env.MODE === 'test'){
        menu_tree.push(modelTest)
      }

      menu_tree.unshift({
        cn_name: "首页",
        en_name: "Home",
        icon: 'icon-shezhi',
        id: "1446387263385777939",
        path: "/app/loong3/home",
        perms: "prj:home",
        pid: "0",
        type: 2,
      })

      this.setUserStoreData({
        dic: dict_data_map,
        currentUser: current_user ?? {},
        menuTree: menu_tree ?? [],
        permsList:perms_list ?? [] });

      return { menu_tree, perms_list }
    },
  },
  persist: piniaPersistConfig("UserState")
})
